package com.tbl.modules.wms.controller.instorage;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.dao.webservice.FewmDAO;
import com.tbl.modules.wms.entity.baseinfo.Externalcable;
import com.tbl.modules.wms.entity.baseinfo.Material;
import com.tbl.modules.wms.entity.instorage.Instorage;
import com.tbl.modules.wms.entity.instorage.InstorageDetail;
import com.tbl.modules.wms.service.baseinfo.ExternalcableService;
import com.tbl.modules.wms.service.baseinfo.MaterialService;
import com.tbl.modules.wms.service.instorage.InstorageDetailService;
import com.tbl.modules.wms.service.instorage.InstorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 入库管理--外采入库
 * @author 70486
 */
@Controller
@RequestMapping(value = "/externalIn")
public class ExternalInController extends AbstractController {

    /**
     * 外协采购电缆
     */
	@Autowired
	private ExternalcableService externalcableService;
    /**
     * 入库详情
     */
	@Autowired
	private InstorageDetailService instorageDetailService;
    /**
     * Webservice服务的接口方法DAO
     */
	@Autowired
	private FewmDAO fewmDAO;
    /**
     * 物料
     */
	@Autowired
	private MaterialService materialService;
    /**
     * 入库管理-入库表
     */
	@Autowired
	private InstorageService instorageService;
	
	/**
	 * 外采入库列表
	 * @return ModelAndView
	 */
	@RequestMapping(value = "/toList")
	@ResponseBody
	public ModelAndView toList() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("techbloom/instorage/externalin/externalin_list");
		return mv;
	}
	
	 /**
     * 弹出到编辑/添加页面
     * @param id 入库明细主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/toAdd.do")
    @ResponseBody
    public ModelAndView toAdd(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/instorage/externalin/externalin_edit");
        InstorageDetail instorageDetail = new InstorageDetail();
        if (id==-1) {
        	mv.addObject("instorageDetail", instorageDetail);
        	mv.addObject("editOrAdd",-1);
        }else {
        	instorageDetail = instorageDetailService.selectById(id);
        	instorageDetail.setQacode_id(
        	        externalcableService.selectOne(new EntityWrapper<Externalcable>().eq("QACODE",instorageDetail.getQaCode())).getId()
            );
        	instorageDetail.setQacode_name(instorageDetail.getQaCode());
        	mv.addObject("instorageDetail", instorageDetail);
        }
        return mv;
    }
	
    /**
     * 保存外采单信息
     * @param instorageDetail 入库明细
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/saveInstorageDetail")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> saveInstorageDetail(InstorageDetail instorageDetail) {
        Map<String, Object> map = new HashMap<>(2);
        boolean result;
        Externalcable externalcable = externalcableService.selectById(instorageDetail.getQaCode());
        //修改
        if(instorageDetail.getId()!=null) {
            instorageDetail.setQaCode(externalcable.getQacode());
            result = instorageDetailService.updateById(instorageDetail);
        }else {
            //新增
            Instorage instorage = new Instorage();
            instorage.setOrderNo(externalcable.getBuyorderno());
            //外采手动录入自定义工单号
            instorage.setEntityNo("WC"+System.currentTimeMillis()/1000);
            instorage.setCreateTime(new Date());
            instorage.setOrderline(String.valueOf(externalcable.getBuyorderline()));
            instorageService.insert(instorage);
            Long wcId = instorage.getId();

            //获取序列
            int seqRfid = fewmDAO.selectSeqRfid();
            String batchno = StringUtils.getNoByDecimalFormat("000000000000","000000000000"+seqRfid,12,"0","");
            //okk
            instorageDetail.setOrg(getSessionUser().getFactoryCode());
            instorageDetail.setBatchNo(batchno);
            instorageDetail.setRfid(batchno);
            instorageDetail.setCreatetime(new Date());
            instorageDetail.setState(1);
            instorageDetail.setPId(instorage.getId());
            instorageDetail.setStoragetype(2L);
            instorageDetail.setInspectno(externalcable.getInspectno());
            instorageDetail.setQaCode(externalcable.getQacode());
            instorageDetail.setMeter(externalcable.getNum().toString());
            instorageDetail.setPId(wcId);
            instorageDetail.setCreatetime(new Date());
            instorageDetail.setConfirmTime(new Date());
            result = instorageDetailService.insert(instorageDetail);

            externalcable.setState(0L);
            externalcableService.updateById(externalcable);
        }
        map.put("result", result);
        map.put("msg", result?"保存成功！":"保存失败！");
        return map;
    }
    
    /**
     * 外采入库获取列表数据
     * @param  queryJsonString 查询条件
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(3);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        PageUtils utils = instorageDetailService.getPagePackageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }
    
    /**
     * 删除外采入库单
     * @param ids 标签初始化主键
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/delExternalin")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> deleteByIds(String[] ids) {
        Map<String, Object> map = Maps.newHashMap();
        List<Long> lstIds = Arrays.stream(ids).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        lstIds.forEach(id->{
        	InstorageDetail instorageDetail = instorageDetailService.selectById(id);
        	if(instorageDetail!=null&&instorageDetail.getPId()!=null){
        		instorageService.deleteById(instorageDetail.getPId());
            }
        });
        boolean result = instorageDetailService.deleteBatchIds(lstIds);
        map.put("msg", result ? "删除成功！" : "删除失败！");
        map.put("result", result);
        return map;
    }
    
    /**
     * 获取质保单号下拉选信息
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/selectQacode")
    @ResponseBody
    public Map<String, Object> selectShelf() {
        Map<String, Object> map = new HashMap<>(2);
        PageTbl page = this.getPage();
        PageUtils utils = externalcableService.getPageQacodeList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("result", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }
    
    /**
     * 根据主键获取下拉框质保单号
     * @param id 入库明细主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getQacode")
    @ResponseBody
    public Map<String, Object> getQacode(String id) {
        Map<String, Object> resultMap = new HashMap<>(2);
        if(StringUtils.isNotEmpty(id)) {
	        InstorageDetail instorageDetail = instorageDetailService.selectById(Long.parseLong(id));
	        Externalcable externalcable = externalcableService.selectOne(new EntityWrapper<Externalcable>().eq("QACODE",instorageDetail.getQaCode()));
	        if(externalcable!=null) {
		        resultMap.put("id", externalcable.getId());
		        resultMap.put("text", externalcable.getQacode());
	        }
        }else {
        	resultMap.put("id", null);
        	resultMap.put("text", null);
        }
        return resultMap;
    }
    
    /**
     * 质保单号下拉选中信息
     * @param externalcableId 外采电缆主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/selectInfo")
    @ResponseBody
    public Map<String, Object> selectInfo(String externalcableId) {
        Map<String, Object> resultMap = new HashMap<>(4);
        Externalcable externalcable = externalcableService.selectById(Long.parseLong(externalcableId));
        resultMap.put("materialCode", externalcable.getMaterialcode());
        resultMap.put("materialName",materialService.selectOne(new EntityWrapper<Material>().eq("CODE",externalcable.getMaterialcode())).getName());
        resultMap.put("meter", externalcable.getNum());
        resultMap.put("qaCode", externalcable.getQacode());
        return resultMap;
    }
    
    /**
     * 确认入库（装包）
     * @param id 入库明细主键
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/changeState")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> changeState(String id) {
        Map<String, Object> map = new HashMap<>(2);
        Long userId = getSessionUser().getUserId();
    	
        //修改状态及保存其他相关信息
        InstorageDetail instorageDetail = instorageDetailService.selectById(id);
        //已包装
        instorageDetail.setState(Constant.INT_TWO);
        instorageDetail.setConfirmTime(new Date());
        instorageDetail.setInstorageTime(new Date());
        instorageDetail.setConfirmBy(userId);
        instorageDetail.setInStorageId(userId);
        
        boolean result = instorageDetailService.updateById(instorageDetail);
    	map.put("result", result);
    	map.put("msg", result?"保存成功！":"保存失败！");
        return map;
    }
    
}
